package com.app.module.camera.core.observer

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.media.ImageReader
import android.util.Log
import android.view.Surface
import com.app.module.camera.task.ImageSaveTask


class TextureCapturer(context:Context) : FramePreviewer(context) {

    private lateinit var imageCapture : ImageReader

    private val imageRanderCallback = object: ImageReader.OnImageAvailableListener{
        override fun onImageAvailable(reader: ImageReader?) {
            Log.e("FrameImageEncoder","imageRander onImageAvailable")
            reader?.acquireLatestImage()?.also {
                close()
                val planes = it.planes
                val first = planes.first()
                val buffer = first.buffer
                val bytes = ByteArray(buffer.remaining())
                buffer.get(bytes)
                val pixelStride: Int = first.pixelStride // 相邻像素采样之间的距离，以字节为单位。
                val rowStride: Int = first.rowStride // 此颜色平面的行跨距，以字节为单位。
                val rowPadding: Int = rowStride - pixelStride * it.width
                ImageSaveTask( it.width + rowPadding / pixelStride ,it.height  ,false).execute(bytes)
                it.close()
            }
        }
    }

    override fun setOutputSize(width: Int, height: Int) {
        super.setOutputSize(width, height)
        initSurface()
    }

    @SuppressLint("WrongConstant")
    fun initSurface(){
        imageCapture = ImageReader.newInstance(getWidth(), getHeight() , PixelFormat.RGBA_8888, 2)
        imageCapture.setOnImageAvailableListener(imageRanderCallback , null)
    }

    override fun setSurface(Surface: Surface) {
    }

    override fun open() {
        super.setSurface(imageCapture.surface)
        super.open()
    }
}
